<template>
  <div class="videoBox" :style="{ width: props.width, height: props.height }">
    <video
      ref="videoRef"
      autoplay
      muted
      style="width: 100%; height: 100%; object-fit: fill"
    ></video>
  </div>
</template>
<script setup>
import { ref, onMounted, onUnmounted,computed } from 'vue'
import flv from 'flv.js'
import { ElMessage } from 'element-plus'

let videoRef = ref()
const flvPlayer = ref(null)
const props = defineProps({
  videoUrl: {
    type: String,
    default:() => 'http://192.168.1.180:8080/live/livestream/c3_big_lobby_front.flv'
  },
  width: {
    type: String,
    default:() => '100%'
  },
  height: {
    type: String,
    default:() => '100%'
  },
  defaultPlayStatus: {
    type: Boolean,
    default: true
  },
  boxBorderColor:{
    type: String,
    default: () => '#ccc'
  }
})
const boxBorderColor = computed(() => props.boxBorderColor)
const emits = defineEmits(['videoError'])

const errorFlag = ref(false)

const createVideo = () => {
  if (flv.isSupported()) {
    flvPlayer.value = flv.createPlayer(
      {
        type: 'flv',
        url: props.videoUrl, //你的url地址
        isLive: true,
        hasAudio: false
      },
      {
        enableWorker: false, //不启用分离线程
        enableStashBuffer: false //关闭IO隐藏缓冲区
        // reuseRedirectedURL: true, //重用301/302重定向url，用于随后的请求，如查找、重新连接等。
        // autoCleanupSourceBuffer: true //自动清除缓存
      }
    )
    flvPlayer.value.attachMediaElement(videoRef.value)
    flvPlayer.value.load()

    setTimeout(function () {
      if (props.defaultPlayStatus) {
        flvPlayer.value.play()
      } else {
        flvPlayer.value.unload()
        flvPlayer.value.pause()
      }
    }, 300)

    flvPlayer.value.on('error', () => {
      errorFlag.value = true
      ElMessage.warning('视频播放失败，请重试!')
      emits('videoError')
    })
  }
}
const destroy = () => {
  flvPlayer.value.pause() //暂停播放数据流
  flvPlayer.value.unload() //取消数据流加载
  flvPlayer.value.detachMediaElement() //将播放实例从节点中取出
  flvPlayer.value.destroy() //销毁播放实例
  flvPlayer.value = null
}

const pause = () => {
  if (flvPlayer.value) {
    flvPlayer.value.pause() //暂停播放数据流
    flvPlayer.value.unload() //取消数据流加载
  }
}

const play = () => {
  if (flvPlayer.value) {
    flvPlayer.value.load() //数据流加载
    flvPlayer.value.play() //暂停播放数据流
  }
}

defineExpose({ destroy, pause, play })

onMounted(() => {
  createVideo()
})

onUnmounted(async () => {
  destroy()
})
</script>
<style scoped>
.videoBox {
  border: solid 1px v-bind('boxBorderColor');
}
</style>
